﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace T4ViewModel
{
    internal class AddeddPropertyInfo
    {
        public string Name { get; set; }
        public Type Type { get; set; }
        public IEnumerable<AddedAttributeInfo> CustomAttributes { get; set; }
    }

    internal class AddedAttributeInfo
    {
        public Attribute Attribute { get; set; }
        public IEnumerable<String> ConstuctorParams { get; set; }
    }

    internal static class ExpressionParser
    {
        public static string GetPropertyName<T, TProperty>(Expression<Func<T, TProperty>> exp)
        {
            MemberExpression memberExp;
            if (!TryFindMemberExpression(exp.Body, out memberExp))
                throw new ArgumentException();

            return memberExp.Member.Name;
        }

        private static bool TryFindMemberExpression(Expression exp, out MemberExpression memberExp)
        {
            memberExp = exp as MemberExpression;
            if (memberExp != null)
            {
                return true;
            }

            if (IsConversion(exp) && exp is UnaryExpression)
            {
                memberExp = ((UnaryExpression)exp).Operand as MemberExpression;
                if (memberExp != null)
                {
                    return true;
                }
            }

            return false;
        }

        private static bool IsConversion(Expression exp)
        {
            return (
                exp.NodeType == ExpressionType.Convert ||
                exp.NodeType == ExpressionType.ConvertChecked
            );
        }
    }
}
